import request from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export function getList(params) {
  return request({
    url: '/systemUser/findSystemUserPage',
    method: 'post',
    data: params
  })
}

export function editUser(params) {
  return request({
    url: '/systemUser/editSystemUser',
    method: 'post',
    data: params
  })
}

export function addUser(params) {
  return request({
    url: '/systemUser/addSystemUser',
    method: 'post',
    data: params
  })
}

// 获取角色下拉
export function getRoleSelect() {
  return request({
    url: '/role/getRoleSelect',
    method: 'get'
  })
}

// 获取部门下拉
export function getDepartmentSelect() {
  return request({
    url: '/department/getDepartmentSelect',
    method: 'get'
  })
}

// 获取角色列表
export function getRoleList() {
  return request({
    url: '/role/getRoleList',
    method: 'get'
  })
}

// 获取部门列表
export function getDepartmentList() {
  return request({
    url: '/department/getDepartmentList',
    method: 'get'
  })
}

// 校验用户名重复
export function validateUsernameRepeat(params) {
  return request({
    url: '/systemUser/validateUsernameRepeat',
    method: 'get',
    params
  })
}

// 在线用户管理
export function getUserOnline() {
  return request({
    url: '/systemUser/getUserOnline',
    method: 'get'
  })
}

// 在线用户强制离线
export function userForceOffline(params) {
  return request({
    url: '/systemUser/userForceOffline',
    method: 'get',
    params
  })
}

export function exportExcel(options = {}) {
  const url = `${process.env.VUE_APP_BASE_API}/systemUser/userListExport`
  return new Promise((resolve, reject) => {
    console.log(`${url} 请求数据，参数=>`, JSON.stringify(options))
    axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    axios.defaults.headers['token'] = getToken()
    axios({
      method: 'post',
      url: url, // 请求地址
      data: options, // 参数
      responseType: 'blob' // 表明返回服务器返回的数据类型
    }).then(
      response => {
        console.log(response)
        resolve(response.data)
        const blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel'
        })
        console.log(blob)
        const fileName = '用户列表.xlsx'
        if (window.navigator.msSaveOrOpenBlob) {
          // console.log(2)
          navigator.msSaveBlob(blob, fileName)
        } else {
          // console.log(3)
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          // 释放内存
          window.URL.revokeObjectURL(link.href)
        }
      },
      err => {
        reject(err)
      })
  })
}
